package ignite.jdbc;


import java.sql.*;

public class JDBC {
    public static void main(String[] args) throws Exception {
//        createTable();
        insertTest();
//        selectTest();
    }

    public static void createTable() {
        try {
            // Register jdbc.JDBC driver.
            Class.forName("org.apache.ignite.IgniteJdbcThinDriver");
            // Open jdbc.JDBC connection.
            Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1/");
            // Create database tables.
            try (Statement stmt = conn.createStatement()) {
                // Create table based on REPLICATED template.
                stmt.executeUpdate("\n" +
                        "CREATE TABLE PUBLIC.person (\n" +
                        "   id INTEGER,\n" +
                        "   firstName VARCHAR,\n" +
                        "   phone VARCHAR,\n" +
                        "   PRIMARY KEY (id)\n" +
                        ")WITH \"template=REPLICATED,CACHE_NAME=person,VALUE_TYPE=org.ignite.entity.Person\";");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void insertTest() throws SQLException {
        Connection conn = null;
        try {
            // Register jdbc.JDBC driver
            Class.forName("org.apache.ignite.IgniteJdbcThinDriver");
// Open jdbc.JDBC connection
            conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1/");
// Populate domain.City table
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //
        try (PreparedStatement stmt =
                     conn.prepareStatement("INSERT INTO public.person values(4412, '张三', '11111111111');")) {
            stmt.executeUpdate();
        }
// Populate domain.Person table
        try (PreparedStatement stmt =
                     conn.prepareStatement("INSERT INTO public.person values(2442, '李四', '11111111111');")) {
            stmt.executeUpdate();
        }
    }

    public static void selectTest() throws Exception {
        // Register jdbc.JDBC driver
        Class.forName("org.apache.ignite.IgniteJdbcThinDriver");
        // Open jdbc.JDBC connection
        Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1/");
        // Get data
        try (Statement stmt = conn.createStatement()) {
            try (ResultSet rs =
                         stmt.executeQuery("SELECT * " +
                                 " FROM public.person")) {
                while (rs.next())
                    System.out.println(rs.getInt(1) + ", " + rs.getString(2) + ", " + rs.getString(3));
            }
        }
    }
}
